package com.jblog.common.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

public abstract class CookieUtils {
	
	public static Cookie readCookie(HttpServletRequest request, String name) {
		Assert.notNull(request);
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (c.getName().equals(name)) {
					return c;
				}
			}
		}
		return null;
	}
	
	public static Cookie writeCookie(HttpServletRequest request,
			HttpServletResponse response, String name, String value, int expiry) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(expiry);
		String ctx = request.getContextPath();
		if (StringUtils.isBlank(ctx)) {
			cookie.setPath("/");
		} else {
			cookie.setPath(ctx);
		}
		response.addCookie(cookie);
		return cookie;

	}

	public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		writeCookie(request, response, name, null, 0);
	}
}
